<template>
  <div class="payment-page">
    <div class="header">
      <h1>订单支付</h1>
    </div>
    
    <el-card class="order-info-card">
      <div class="card-title">订单信息</div>
      <div class="order-info">
        <div class="info-item">
          <span class="info-label">订单编号：</span>
          <span class="info-value">{{ orderInfo.orderNo }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">下单时间：</span>
          <span class="info-value">{{ formatDate(orderInfo.createdAt) }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">订单金额：</span>
          <span class="info-value amount">¥{{ orderInfo.payAmount }}</span>
        </div>
      </div>
    </el-card>
    
    <el-card class="payment-method-card">
      <div class="card-title">选择支付方式</div>
      <div class="payment-methods">
        <el-radio-group v-model="paymentMethod">
          <el-radio :label="1">
            <div class="payment-option">
              <i class="el-icon-wechat"></i>
              <span>微信支付</span>
            </div>
          </el-radio>
          <el-radio :label="2">
            <div class="payment-option">
              <i class="el-icon-alipay"></i>
              <span>支付宝</span>
            </div>
          </el-radio>
          <el-radio :label="3">
            <div class="payment-option">
              <i class="el-icon-bank-card"></i>
              <span>银行卡支付</span>
            </div>
          </el-radio>
        </el-radio-group>
      </div>
    </el-card>
    
    <el-card class="payment-detail-card" v-if="paymentMethod">
      <div class="card-title">支付详情</div>
      <div class="payment-detail">
        <div class="payment-qr" v-if="paymentMethod === 1 || paymentMethod === 2">
          <div class="qr-placeholder">
            <i class="el-icon-picture-outline"></i>
            <p>扫码支付区域</p>
          </div>
          <p class="payment-tip">请使用{{ paymentMethod === 1 ? '微信' : '支付宝' }}扫描二维码完成支付</p>
        </div>
        <div class="bank-card-form" v-if="paymentMethod === 3">
          <el-form :model="bankCardForm" label-width="100px">
            <el-form-item label="银行卡号">
              <el-input v-model="bankCardForm.cardNumber" placeholder="请输入银行卡号"></el-input>
            </el-form-item>
            <el-form-item label="持卡人姓名">
              <el-input v-model="bankCardForm.cardHolder" placeholder="请输入持卡人姓名"></el-input>
            </el-form-item>
            <el-form-item label="有效期">
              <el-input v-model="bankCardForm.expiryDate" placeholder="MM/YY"></el-input>
            </el-form-item>
            <el-form-item label="CVV">
              <el-input v-model="bankCardForm.cvv" placeholder="请输入CVV"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
    
    <div class="payment-actions">
      <el-button type="primary" size="large" @click="simulatePayment" :loading="isPaying">
        {{ isPaying ? '支付中...' : '模拟支付' }}
      </el-button>
      <el-button size="large" @click="cancelPayment">取消支付</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderService } from '../services/orderService'

const route = useRoute()
const router = useRouter()

// 订单信息
const orderInfo = ref({
  id: '',
  orderNo: '',
  createdAt: '',
  payAmount: 0
})

// 支付方式（默认微信支付）
const paymentMethod = ref(1)

// 银行卡表单
const bankCardForm = ref({
  cardNumber: '',
  cardHolder: '',
  expiryDate: '',
  cvv: ''
})

// 支付状态
const isPaying = ref(false)

// 加载订单信息
const loadOrderInfo = async () => {
  try {
    const orderId = route.params.id
    if (!orderId) {
      ElMessage.error('订单ID不存在')
      router.push('/orders')
      return
    }
    
    // 获取订单详情
    const result = await orderService.getOrderDetail(orderId)
    
    if (result && result.id) {
      orderInfo.value = {
        id: result.id,
        orderNo: result.orderNo,
        createdAt: result.createdAt,
        payAmount: result.payAmount
      }
    } else {
      ElMessage.error('获取订单信息失败')
      router.push('/orders')
    }
  } catch (error) {
    console.error('获取订单信息失败:', error)
    
    // 处理401错误
    if (error.statusCode === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('获取订单信息失败')
      router.push('/orders')
    }
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
}

// 获取支付方式名称
const getPaymentMethodName = (method) => {
  const methods = {
    1: '微信支付',
    2: '支付宝',
    3: '银行卡支付',
    4: '货到付款'
  }
  return methods[method] || '未知支付方式'
}

// 模拟支付
const simulatePayment = async () => {
  try {
    isPaying.value = true
    
    // 验证支付方式是否已选择
    if (!paymentMethod.value) {
      ElMessage.warning('请选择支付方式')
      return
    }
    
    // 根据不同的支付方式添加不同的验证
    if (paymentMethod.value === 3) {
      // 银行卡支付需要验证表单
      if (!bankCardForm.value.cardNumber || !bankCardForm.value.cardHolder || 
          !bankCardForm.value.expiryDate || !bankCardForm.value.cvv) {
        ElMessage.warning('请完善银行卡信息')
        return
      }
      
      // 简单的银行卡号格式验证
      if (bankCardForm.value.cardNumber.length < 16) {
        ElMessage.warning('请输入正确的银行卡号')
        return
      }
      
      // CVV格式验证
      if (bankCardForm.value.cvv.length < 3) {
        ElMessage.warning('请输入正确的CVV码')
        return
      }
    }
    
    // 模拟支付处理时间
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    console.log('开始支付，订单ID:', orderInfo.value.id, '支付方式:', paymentMethod.value)
    
    // 调用支付接口，传递支付方式
    const result = await orderService.payOrder(orderInfo.value.id, paymentMethod.value)
    
    if (result) {
      ElMessage.success('支付成功！')
      
      // 显示支付成功信息
      ElMessageBox.alert(
        `订单号：${orderInfo.value.orderNo}\n支付金额：¥${orderInfo.value.payAmount.toFixed(2)}\n支付方式：${getPaymentMethodName(paymentMethod.value)}`,
        '支付成功',
        {
          confirmButtonText: '查看订单',
          type: 'success'
        }
      ).then(() => {
        // 跳转到订单列表页
        router.push('/orders')
      })
      
    } else {
      ElMessage.error('支付失败，请重试')
    }
  } catch (error) {
    console.error('支付失败:', error)
    
    // 处理401错误
    if (error.statusCode === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
    } else if (error.statusCode === 400) {
      ElMessage.error('支付参数错误，请检查订单信息')
    } else if (error.statusCode === 404) {
      ElMessage.error('订单不存在或已过期')
      router.push('/orders')
    } else {
      ElMessage.error('支付失败，请稍后重试')
    }
  } finally {
    isPaying.value = false
  }
}

// 取消支付
const cancelPayment = () => {
  ElMessageBox.confirm('确定要取消支付吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '继续支付',
    type: 'warning'
  }).then(() => {
    // 跳转到订单列表页
    router.push('/orders')
  }).catch(() => {
    // 用户选择继续支付，不做任何操作
  })
}

// 页面加载时初始化数据
onMounted(() => {
  loadOrderInfo()
})
</script>

<style scoped>
.payment-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.header h1 {
  font-size: 28px;
}

.order-info-card,
.payment-method-card,
.payment-detail-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  padding: 20px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.info-label {
  color: #666;
}

.info-value {
  color: #333;
}

.info-value.amount {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 18px;
}

.payment-methods {
  padding: 20px;
}

.payment-option {
  display: flex;
  align-items: center;
  gap: 10px;
}

.payment-option i {
  font-size: 20px;
}

.payment-detail {
  padding: 20px;
}

.payment-qr {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.qr-placeholder {
  width: 200px;
  height: 200px;
  border: 1px dashed #ddd;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.qr-placeholder i {
  font-size: 40px;
  color: #ddd;
  margin-bottom: 10px;
}

.payment-tip {
  color: #666;
  text-align: center;
}

.bank-card-form {
  max-width: 500px;
}

.payment-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}
</style>